package com.bskj.kuaifu.MQLister;

import com.bskj.common.utils.LogUtils;
import com.bskj.kuaifu.service.IPayInfoService;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * Created by mocaijin on 06/03/2018.
 * 处理充值支付的回调逻辑
 */
public class PayInfoMessageListener implements ChannelAwareMessageListener {
    @Autowired
    private WXPay wxPay;

    @Autowired
    private IPayInfoService payInfoService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {

        String xmlStr = new String(message.getBody(), "UTF-8");
        LogUtils.debug(xmlStr);
        boolean deleteMessageFlag = true;
        try {
            Map<String, String> notifyMap = wxPay.processResponseXml(xmlStr);
            String return_code = notifyMap.get("return_code");
            if (return_code.equals(WXPayConstants.SUCCESS)) {
                Map<String, Object> resultMap = payInfoService.finishedBalancePay(notifyMap, true);
            }
        } catch (Exception e) {
            deleteMessageFlag = false;
            e.printStackTrace();
        }

        if (deleteMessageFlag) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            //multiple:false:是否批量.true:将一次性拒绝所有小于deliveryTag的消息，requeue：true被拒绝的是否重新入队列，
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }

}
